package com.ysfxt.jwt;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author 盐酸氟西汀
 * @create 2024/3/29 11:08
 * @email 480738950@qq.com
 */
public class JwtHelper {
    //过期时间，7天
    private static long tokenExpiration = 7 * 24 * 60 * 60 * 1000;
    private static String tokenSignKey = "123456ysfxt";
    
    public static String createToken(Long userId, String type) {
        String token = Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("type", type)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) return null;
            
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static String getType(String token) {
        try {
            if (StringUtils.isEmpty(token)) return "";
            
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("type");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    //判断token是否有效
    public static boolean isExpiration(String token){
        try {
            boolean isExpire = Jwts.parser()
                    .setSigningKey(tokenSignKey)
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration().before(new Date());
            //没有过期，有效，返回false
            return isExpire;
        }catch(Exception e) {
            //过期出现异常，返回true
            return true;
        }
    }
    
    public static void main(String[] args) {
        String token = JwtHelper.createToken(1L, "user_login:");
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getType(token));
    }
}